﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Apache.NMS;
using Apache.NMS.Util;
using Apache.NMS.ActiveMQ;
namespace PMC
{
     public class MQHelper
    {

        private static IConnectionFactory connFac;



        private static IConnection connection;

        private static ISession session;

        private static IDestination destination;

        private static IMessageProducer producer;

        



        /// <summary>

        /// 初始化ActiveMQ

        /// </summary>

        public static void initAMQ()
        {


            String url = "activemq:failover:(TCP://127.0.0.1:61616/)";
            String Destination = "PLC_PMC_TagValueChange";

            try
            {

                connFac = new NMSConnectionFactory(new Uri(url)); 

                connection = connFac.CreateConnection();

                //创建Session

                session = connection.CreateSession();
                destination = SessionUtil.GetDestination(session, Destination);          
                producer = session.CreateProducer(destination);
                producer.DeliveryMode = MsgDeliveryMode.Persistent;

            }

            catch (Exception e)
            {
                Console.WriteLine(e.Message);

                Console.WriteLine("初始化ActiveMQ失败");

            }

        }



        /// <summary>

        /// 推送ActiveMQ

        /// </summary>

        /// <param name="guid"></param>

        /// <param name="t"></param>

        /// <param name="method"></param>

        public static void Send(String Message)
        {

            if (producer == null)
            {
                initAMQ();
            }

            if (session == null)
            {
                throw new Exception("请初始化ActiveMQ！");
            }

            if (producer == null)
            {

                throw new Exception("请初始化ActiveMQ！");

            }

            ITextMessage msg = session.CreateTextMessage(Message);
            producer.Send(msg, Apache.NMS.MsgDeliveryMode.Persistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);

        }


    }
}
